import json

from selenium import webdriver
from selenium.webdriver.common.by import By

from spider_h5.seleinum_bankend.pojo.applet_info import AppletInfo
from spider_h5.seleinum_bankend.utils.logger import log
from spider_h5.seleinum_bankend.utils.mongo_utils import DBRoc



"""
Description:
Service主要是一些业务方法
"""

class AppletPageService(object):

    def __init__(self, client,name):
        self.browser: webdriver = client.browser
        self.name=name

    def save_applet_info(self):
        """
        Description: 保存商家信息
        """
        page_elements = self.browser.find_elements(By.XPATH, '/html/body/div[1]/div[2]/div/div/div/div/div[2]/div[2]/div[1]/ul/li')
        total_applet_count=self.browser.find_element(By.XPATH,'/html/body/div[1]/div[2]/div/div/div/div/div[2]/div[2]/div[2]/div').text
        print(f'applet的总数量是{total_applet_count}')
        # 页数切换
        page_elements=self.browser.find_elements(By.XPATH,'/html/body/div[1]/div[2]/div/div/div/div/div[2]/div[2]/div[1]/ul/li')
        click_number=len(page_elements)-3 if len(page_elements)>0 else 0
        applet_list = []
        for record in range(click_number):
            # 每次切换页面时需要进行重新加载页码项
            page_elements = self.browser.find_elements(By.XPATH, '/html/body/div[1]/div[2]/div/div/div/div/div[2]/div[2]/div[1]/ul/li')
            applet_data=self.browser.find_elements(By.XPATH, '/html/body/div[1]/div[2]/div/div/div/div/div[2]/div[1]/table/tbody/tr')
            for applet in applet_data:
                # 获取数据
                applet_id=applet.find_element(By.XPATH, './td[1]').text
                applet_src=applet.find_element(By.XPATH, './td[2]/img').get_property('src')
                applet_name=applet.find_element(By.XPATH, './td[3]/p').text
                group_name=applet.find_element(By.XPATH,'./td[4]/p').text
                create_time=applet.find_element(By.XPATH,'./td[8]').text.strip()
                expired_time=applet.find_element(By.XPATH,'./td[9]').text.strip()
                setting_url=applet.find_elements(By.XPATH, './/*[@class="tpl-table-black-operation"]/a')[0].get_property('href')
                manage_url=applet.find_elements(By.XPATH, './/*[@class="tpl-table-black-operation"]/a')[1].get_property('href')
                applet_info=AppletInfo(applet_id=applet_id,applet_image_url=applet_src,applet_name=applet_name,group_name=group_name,create_time=create_time,expired_time=expired_time,setting_url=setting_url,manage_url=manage_url)
                applet_list.append(applet_info.to_dict())
            if record ==click_number-1:
                break
            next_url=page_elements[len(page_elements)-1].find_element(By.XPATH, './a').get_property('href')
            self.browser.get(next_url)
            self.browser.implicitly_wait(10)
        log(f"实际获取的Applet共{len(applet_list)}个，内容如下{json.dumps(applet_list, ensure_ascii=False)}")
        DBRoc(name=self.name).insert_many(applet_list)


    def clear_collection(self):
        """
        清空集合数据，相当于一张表
        """
        DBRoc(name=self.name).delete_many({})

    def enter_applet_id(self,applet_id):
        """
        进入一个小程序ID
        Params:
        applet_id:小程序ID
        """
        record=DBRoc(name=self.name).find_one({'applet_id':applet_id})
        if record:
            target_url=record['manage_url']
            self.browser.get(target_url)
            return True
        else:
            return False









